import 'dart:async';

import 'package:flutter/material.dart';

class CustomKeepAliveWrapper extends StatefulWidget {
  const CustomKeepAliveWrapper({super.key});
  @override
  State<CustomKeepAliveWrapper> createState() => _PageViewPageState();
}

class _PageViewPageState extends State<CustomKeepAliveWrapper> {
  List<Widget> pageList = [];
  @override
  void initState() {
    List listData = [
      {
        "imageUrl": 'https://www.itying.com/images/flutter/1.png',
      },
      {
        "imageUrl": 'https://www.itying.com/images/flutter/2.png',
      },
      {
        "imageUrl": 'https://www.itying.com/images/flutter/3.png',
      }
    ];
    for (int i = 0; i < listData.length; ++i) {
      pageList.add(PicturePage(
        //集合 里面就是加载了3个 图片的View
        url: listData[i]["imageUrl"],
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("pageview演示"),
        ),
        body: ListView(
          //body: Column(
          children: [Swiper(pageList: pageList)], // 把图片集合传递给一个自定义组件Swipper
        ));
  }
}

//Swiper组件
class Swiper extends StatefulWidget {
  final double width;
  final double height;
  final List<Widget> pageList;
  const Swiper(
      {super.key,
      this.width = double.infinity,
      this.height = 200,
      required this.pageList});
  @override
  State<Swiper> createState() => _SwiperState();
}

class _SwiperState extends State<Swiper> {
  //就是一个组件，报过了 3个pageList，每个pageList 里面的元素就是一张图片，构成banner
  int _currentPageIndex = 0;
  late PageController _pageController;
  late Timer timer;
  @override
  void initState() {
    super.initState();
    print('initState');
    _pageController = PageController(initialPage: 0);

    const timeout = Duration(seconds: 3);
    timer = Timer.periodic(timeout, (timer) {
      print(
          'periodic _currentPageIndex:  $_currentPageIndex    pagelist.length:${widget.pageList.length}');
      _pageController.animateToPage(
          (_currentPageIndex + 1) % (widget.pageList.length),
          curve: Curves.linear,
          duration: const Duration(milliseconds: 200));
    });
  }

  @override
  void dispose() {
    super.dispose();
    timer.cancel();
    _pageController.dispose();
    print('dispose...');
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // SizedBox(
        SizedBox(
          width: double.infinity,
          height: 200,
          // padding: EdgeInsets.only(left: 10,right: 10),
          child: PageView.builder(
              controller: _pageController,
              scrollDirection: Axis.horizontal,
              onPageChanged: (int index) {
                // 在onPageChanged  方法里面监听 PageView 的变化，获取_currentPageIndex 值，就是当前是PageView 的index
                setState(() {
                  _currentPageIndex = index %
                      (widget.pageList
                          .length); // 通过取余运算，获取当前 _currentPageIndex 的余数，作为ImageView对应的Banner 的index

                  print(
                      'setState  _currentPageIndex:$_currentPageIndex   index:$index');
                });
              },
              itemCount: 10,
              itemBuilder: (context, index) {
                //创建了一千个 PageView
                return KeepAliveWrapper(
                  child: widget.pageList[index % (widget.pageList.length)],
                  keepAlive: true,
                );
                ;
              }),
        ),
        Positioned(
          bottom: 10,
          left: 0,
          right: 0,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(widget.pageList.length, (i) {
              //遍历创建三个点，以 当前banner 对应的index 作为选中的item 图标，着重凸显显示。
              return Container(
                margin: const EdgeInsets.fromLTRB(2, 0, 2, 0),
                width: 10,
                height: 10,
                decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: _currentPageIndex == i ? Colors.blue : Colors.grey),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}

//PicturePage 图片页面
class PicturePage extends StatefulWidget {
  final String url;
  final double width;
  final double height;
  const PicturePage(
      {super.key,
      required this.url,
      this.width = double.infinity,
      this.height = 200});
  @override
  State<PicturePage> createState() => _PicturePageState();
}

class _PicturePageState extends State<PicturePage> {
  @override
  Widget build(BuildContext context) {
    print(widget.url);
    return Container(
        width: widget.width,
        height: widget.height,
        padding: EdgeInsets.only(left: 10, right: 10),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(6)),
          child: Image.network(widget.url, fit: BoxFit.cover),
        ));
  }
}

class KeepAliveWrapper extends StatefulWidget {
  const KeepAliveWrapper(
      {Key? key, @required this.child, this.keepAlive = true})
      : super(key: key);
  final Widget? child;
  final bool keepAlive;
  @override
  State<KeepAliveWrapper> createState() => _KeepAliveWrapperState();
}

class _KeepAliveWrapperState extends State<KeepAliveWrapper>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    return widget.child!;
  }

  @override
  bool get wantKeepAlive => widget.keepAlive;
  @override
  void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
    if (oldWidget.keepAlive != widget.keepAlive) {
// keepAlive 状态需要更新，实现在 AutomaticKeepAliveClientMixin 中
      updateKeepAlive();
    }
    super.didUpdateWidget(oldWidget);
  }
}
